package util.conversor;

import syntaxtree.ArrayAssign;
import syntaxtree.Assign;
import syntaxtree.Block;
import syntaxtree.Exp;
import syntaxtree.Identifier;
import syntaxtree.If;
import syntaxtree.Print;
import syntaxtree.Statement;
import syntaxtree.While;
import util.List;
import minijava.analysis.AnalysisAdapter;
import minijava.node.AIdArrayStatStatement;
import minijava.node.AIdStatStatement;
import minijava.node.AIfStatStatement;
import minijava.node.ALstatrStatement;
import minijava.node.APrintStatStatement;
import minijava.node.AWhileStatStatement;
import minijava.node.PStatement;
import minijava.node.Token;

class StatementHandler extends AnalysisAdapter
{
	private Statement result;
	
	public StatementHandler()
	{
		super();
	}
	
	static Statement convert(PStatement node)
	{
		StatementHandler h = new StatementHandler();
		
		node.apply(h);
		
		return h.result;
	}

	public void caseALstatrStatement(ALstatrStatement node)
	{
		Token t = node.getLeftbra();
		List<Statement> ss = StatementListHandler.convert(node.getStatement());
		
		result = new Block(t.getLine(), t.getPos(), ss);
	}
	
	public void caseAWhileStatStatement(AWhileStatStatement node)
	{
		Exp c = ExpHandler.convert(node.getExp());
		Statement b = StatementHandler.convert(node.getStm());
		Token t = node.getWhile();
		
		result = new While(t.getLine(), t.getPos(), c, b);
	}
	
	public void caseAIfStatStatement(AIfStatStatement node)
	{
		Exp c = ExpHandler.convert(node.getExp());
		Statement t = StatementHandler.convert(node.getStm1());
		Statement e = node.getStm2() == null ? null : StatementHandler.convert(node.getStm2());
		Token tt = node.getIf();
		
		result = new If(tt.getLine(), tt.getPos(), c, t, e);
	}
	
	public void caseAPrintStatStatement(APrintStatStatement node)
	{
		Exp value = ExpHandler.convert(node.getExp());
		Token t = node.getPrint();
		
		result = new Print(t.getLine(), t.getPos(), value);
	}
	
	public void caseAIdStatStatement(AIdStatStatement node)
	{
		Token t = node.getId();
		Exp value = ExpHandler.convert(node.getExp());
		
		Identifier id = new Identifier(t.getLine(), t.getPos(), t.getText());
		
		result = new Assign(id.line, id.row, id, value);
	}
	
	public void caseAIdArrayStatStatement(AIdArrayStatStatement node)
	{
		Token t = node.getId();
		Exp index = ExpHandler.convert(node.getExp1());
		Exp value = ExpHandler.convert(node.getExp2());
		
		Identifier id = new Identifier(t.getLine(), t.getPos(), t.getText());
		
		result = new ArrayAssign(id.line, id.row, id, index, value);
	}
}
